package com.biz.service.basic;

import com.alibaba.druid.util.Utils;
import com.biz.model.Hmodel.TBaseUser;
import com.biz.model.Hmodel.TSysUser;
import com.biz.model.Hmodel.basic.Tpics;
import com.biz.model.Pmodel.PBaseUser;
import com.biz.model.Pmodel.SysUser;
import com.biz.model.Pmodel.User;
import com.biz.model.Pmodel.sys.Puser;
import com.biz.service.base.BaseServiceImpl;
import com.framework.dao.hdao.BaseDaoI;
import com.framework.dao.mdao.DaoSupport;
import com.framework.model.Paging;
import com.framework.model.Params;
import com.framework.utils.ConfigUtil;
import com.framework.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by yzljj on 2016/6/23.
 */
@Service("userService")
public class UserServiceImpl extends BaseServiceImpl<User> implements UserServiceI {
    @Autowired
    private BaseDaoI<TSysUser> userDao;
    @Autowired
    private BaseDaoI<Tpics> picDao;
    @Autowired
    private BaseDaoI<TBaseUser> baseUserDao;
    @Resource(name = "daoSupport")
    private DaoSupport dao;
    @Override
    public User findByName(String username) {
        User user=new User();
        String hql= StringUtil.formateString("from TSysUser where login_name='{0}' and isdel=0 and islock=0",username);
        TSysUser tUser= userDao.getByHql(hql);
        if (tUser!=null){

            BeanUtils.copyProperties(tUser,user);
            user.setId(tUser.getUser_code());
            user.setUsername(tUser.getLogin_name());
            user.setPassword(tUser.getPwd());
            user.setPerson_name(tUser.getPerson_name());
            user.setIdentity(tUser.getIdentity());
            user.setIdentity_code(tUser.getIdentity_code());
            if(!StringUtil.isNullOrEmpty(tUser.getPic_url())) {
               user.setHeadUrl(tUser.getPic_url());
            }

            return user;
        }else{
            return  null;
        }

    }

    @Override
    public List<Map> findRolesByUser(User user){
      String sql=  StringUtil.formateString("SELECT\n" +
                "\ta.*\n" +
                "FROM\n" +
                "\tt_role a\n" +
                "LEFT JOIN t_user_role b ON a.id = b.role_id\n" +
                "LEFT JOIN t_user c ON c.id = b.user_id\n" +
                "WHERE\n" +
                "\tc.username = '{0}'",user.getUsername());
        List<Map> list= userDao.findBySql(sql);
        return list;
    }


    @Override
    public List<Map> findNameSpaceRolesByUser(User user){
        String sql=  StringUtil.formateString("SELECT\n" +
                "\tz.id,\n" +
                "\tz.roleName,\n" +
                "\tz.roleGroup,\n" +
                "\tz.roleMark,\n" +
                "\tz.iconCls,\n" +
                "\tz.isdel,\n" +
                "\tz.createTime,\n" +
                "\tGROUP_CONCAT(z.permission)  as permission\n" +
                "FROM\n" +
                "\t(\n" +
                "\t\tSELECT\n" +
                "\t\t\ta.id,\n" +
                "\t\t\ta.roleName,\n" +
                "\t\t\ta.roleGroup,\n" +
                "\t\t\ta.roleMark,\n" +
                "\t\t\ta.iconCls,\n" +
                "\t\t\ta.isdel,\n" +
                "\t\t\ta.createTime,\n" +
                "\t\t\trm.permission_nameSpace AS permission\n" +
                "\t\tFROM\n" +
                "\t\t\tt_role a\n" +
                "\t\tLEFT JOIN t_user_role b ON a.id = b.role_id\n" +
                "\t\tLEFT JOIN sys_user c ON c.user_code = b.user_id\n" +
                "\t\tLEFT JOIN t_sys_role_menu rm ON rm.role_id = a.id\n" +
                "\t\tWHERE\n" +
                "\t\t\tc.login_name = '{0}'\n" +
                "\t\tGROUP BY\n" +
                "\t\t\ta.id,\n" +
                "\t\t\trm.permission_nameSpace\n" +
                "\t) AS z\n" +
                "GROUP BY\n" +
                "\tz.id",user.getUsername());
        List<Map> list= userDao.findBySql(sql);
        return list;
    }


    @Override
    public List<Map> findPermissionList(User user){
        String sql=  StringUtil.formateString("SELECT\n" +
                "\t\t\ta.id,\n" +
                "\t\t\ta.roleName,\n" +
                "\t\t\ta.roleGroup,\n" +
                "\t\t\ta.roleMark,\n" +
                "\t\t\ta.iconCls,\n" +
                "\t\t\ta.isdel,\n" +
                "\t\t\ta.createTime,\n" +
                "\t\t\trm.permission_nameSpace AS permission\n" +
                "\t\tFROM\n" +
                "\t\t\tt_role a\n" +
                "\t\tLEFT JOIN t_user_role b ON a.id = b.role_id\n" +
                "\t\tLEFT JOIN sys_user c ON c.user_code = b.user_id\n" +
                "\t\tLEFT JOIN t_sys_role_menu rm ON rm.role_id = a.id\n" +
                "\t\tWHERE\n" +
                "\t\t\tc.login_name = '{0}'\n" +
                "\t\tGROUP BY\n" +
                "\t\t\ta.id,\n" +
                "\t\t\trm.permission_nameSpace",user.getUsername());
        List<Map> list= userDao.findBySql(sql);
        return list;
    }




    @Override
    public Paging findAgentUserGrid(Params sqlParams) throws Exception {
        Paging paging= dao.findForPagings("userDao.findAgentUserGrid",sqlParams,"userDao.findAgentUserCount",sqlParams);
        return paging;
    }

    @Override
    public String findIdentity_code(User user) throws Exception {
        return (String)dao.findForObject("userDao.findIdentity_code",user.getUsername());
    }

    @Override
    public User findUser(User user) throws Exception {
        return (User)dao.findForObject("userDao.findUser",user.getUsername());
    }

    @Override
    public User findUserByUserName(String userName) throws Exception {
        return (User)dao.findForObject("userDao.findUserByUserName",userName);
    }




    //获取是否有分期发券权限(是否分期 0：不分期  1：分期)
    @Override
    public int findBaseUserisPeriodization(int identity,String identity_code) throws Exception {
        return 0;
    }

    /**
     * 登录判断
     * @param hashMap
     * @return
     * @throws Exception
     */
    public User getUserForLoginhashMap(HashMap<String, Object> hashMap) throws Exception
    {
        return (User) dao.findForObject("userDao.getUserForLoginhashMap", hashMap);
    }


    @Override
    public User getUserByCode(String user_code) throws Exception {
        Map<String,String> map=new HashMap<>();
        map.put("userCode",user_code);
        return (User) dao.findForObject("userDao.getUserByCode",map);
    }

    @Override
    public boolean changePwd(String pwd,String userid)throws Exception{
        try{
            String hql= StringUtil.formateString("from TSysUser where id='{0}' ",userid);
            TSysUser tUser= userDao.getByHql(hql);
            tUser.setPwd(pwd);
            userDao.update(tUser);
            return true;
        }catch(Exception e){
            e.printStackTrace();
            return false;
        }

    }

    @Override
    public String findSidByCode(String identity_code) throws Exception {
        return (String)dao.findForObject("userDao.findSidByCode",identity_code);
    }

    public PBaseUser getBaseUserByOpen_id(String open_id) throws Exception
    {
        return (PBaseUser) dao.findForObject("userDao.getBaseUserByOpen_id", open_id);
    }

    public Map<String,Object> upDateAgentsByOpenId(String openId)
    {
        Map<String,Object> map=new HashMap<>();
        try{
            PBaseUser baseUser =getBaseUserByOpen_id(openId);

            //更新微信用户
            TBaseUser  tbaseUser =baseUserDao.getById(TBaseUser.class, baseUser.getId());
            tbaseUser.setIdentity(3);
            baseUserDao.update(tbaseUser);
            //插入系统用户
            TSysUser tuser=new TSysUser();
            tuser.setIdentity(3);
            tuser.setType(2);
            tuser.setIsdel( 0);
            tuser.setLogin_name(tbaseUser.getPhone());
            tuser.setPwd(Utils.md5(tbaseUser.getPhone()));
            tuser.setPhone(tbaseUser.getPhone());
            tuser.setPerson_name(tbaseUser.getPersonName());
            tuser.setSort(Integer.valueOf(99));
            //tuser.setState(1);
            tuser.setIslock(0);
            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
            tuser.setCreate_time(new Date());
           /* tuser.setBaseUserId(tbaseUser.getId());
            tuser.setProfit(100.0);*/
            userDao.save(tuser);
            //“一级代理商”默认设置权限
            updateUserRole(ConfigUtil.get("agent1_roleId"), tuser.getUser_code());
            map.put("success",true);
        }
        catch (Exception e)
        {
            map.put("success",false);
        }

        return map;
    }

    public void updateUserRole(String roles,String userId) throws Exception{
        dao.delete("roleDao.deleteUserRoles",userId);

        if(roles!=null && !roles.trim().equals(""))
        {
            Map userRole ;
            String [] rolesArray = roles.split(",");
            for(int i=0;i<rolesArray.length;i++)
            {
                userRole = new HashMap();
                userRole.put("code", UUID.randomUUID().toString());
                userRole.put("userId",userId);
                userRole.put("roleId",rolesArray[i]);
                dao.save("roleDao.saveUserRole",userRole);
            }
        }
    }

    @Override
    public Integer checkLoginName(String loginName) throws Exception {
        Map<String, Object> map=new HashMap<String, Object>();
        map.put("loginName", loginName);
        return (Integer) dao.findForObject("userDao.checkLoginNameByMap", map);
    }
    @Override
    public List<Puser> findPhone(String phone) throws Exception {
        return (List<Puser>) dao.findForList("userDao.findPhone", phone);
    }

    @Override
    public Map<String, String> getIdentityInfoByUser(SysUser user) throws Exception {
        Map<String,String> identityInf=new HashMap<>();
        if("2".equals(user.getIdentity()+""))
        {
            identityInf= (Map<String, String>) dao.findForObject("agentMapper.getById",user.getIdentity_code());
        }else if ("3".equals(user.getIdentity()+""))
        {   identityInf= (Map<String, String>) dao.findForObject("brandMapper.getById",user.getIdentity_code());}
        else if("4".equals(user.getIdentity()+""))
        {  identityInf= (Map<String, String>) dao.findForObject("shopDao.getById",user.getIdentity_code());}
        return identityInf;
    }
}
